package org.brisling.base.service;

import java.util.ArrayList;
import java.util.List;

import org.brisling.base.domain.inf.BaseTreeDomainInf;
import org.brisling.base.repository.BaseTreeRepository;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * 树结构业务基础service，所有树结构业务对象必须继承该service类
 * @author : jackson wang
 * @Date   : 2015年6月8日 下午8:17:42
 * @version: 1.0
 */
public class BaseTreeService<T extends BaseTreeDomainInf> extends BaseService<T>{

	protected String openState="closed";
	
	protected String closeState="open";
	
	
	protected BaseTreeRepository<T,Long> baseRepo;
	
	@Autowired
	protected void setService(BaseTreeRepository<T,Long> baseRepo){
		this.baseRepo = baseRepo;
		super.setService(baseRepo);
	}
	
	public List<T> getRootNode(Long id){
		
		List<T> lists = new ArrayList<T>();
		if(id==null)
			lists = baseRepo.findByParentidIsNull(defaultSort);
		else{
			T t = baseRepo.findOne(id);
			lists.add(t);
		}
		
		if(lists!=null&&lists.size()>0){
			
			for(int i=0;i<lists.size();i++){
				List<T> childrens = baseRepo.findByParentid(lists.get(i).getId(),defaultSort);
				
				if(childrens!=null&&childrens.size()>0){
					//children is not null					
					//Set set = new HashSet(Arrays.asList(childrens));
					lists.get(i).setState(openState);
				}else{
					//leaf node,childrens is null
					lists.get(i).setState(closeState);
				}
			}
			
		}
		
		return lists;
	}
	
	public List<T> getNode(Long id){
		
		
		List<T> list = baseRepo.findByParentid(id,this.defaultSort);
		for(int i=0;i<list.size();i++){
//			List<? extends HierachicalBeanDataModeler> childrens = repo.findByParentid(list.get(i).getId(),sort);
//			
//			if(childrens!=null&&childrens.size()>0){
//				//children is not null					
//				//Set set = new HashSet(Arrays.asList(childrens));
//				list.get(i).setState(openState);
//			}else{
//				//leaf node,childrens is null
//				list.get(i).setState(closeState);
//			}
			list.get(i).setState(openState);
		}
		return list;
	}
	
	
	public T save(T t){
		
		if(t!=null){
			//传人值不为空
			
			String parentBizcode = "";
			String childFullBizcode = "";
			Long _parentid =t.getParentid();
			if((_parentid!=null)&&(_parentid.toString().trim().length()>0)){
				//传人entity parentid不为空			
				T parent = this.getOne(_parentid);				
				if(parent!=null){
					//获取上级完整业务编码
					parentBizcode = parent.getFullBizcode();
					if((parentBizcode!=null)&&(parentBizcode.trim().length()>0)){
						childFullBizcode =parentBizcode;
					}
				}							
			}
			
			//获取本级业务编码
			String childBizcode = t.getBizcode();
			if((childBizcode!=null)&&(childBizcode.trim().length()>0)){
				childFullBizcode =childFullBizcode==""?childBizcode:childFullBizcode +":" + childBizcode;
			}
			//本级完整业务编码 = 上级完整业务编码  + 本级业务编码
			t.setFullBizcode(childFullBizcode);	
		}
		return super.save(t);
	}	
}
